package com.sky.task;

import cn.hutool.core.util.ObjectUtil;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author Administrator
 * @version 1.0
 * @description: 订单状态定时任务处理类
 * @date 2023/9/25 9:01
 */
@Slf4j
@Component
public class OrderTask {
    @Autowired
    private OrderMapper orderMapper;

    /**
     * 超时订单处理（周期：每分钟执行一次）
     */
//    @Scheduled(cron = "0 0/1 * * * ?")
    public void processTimeoutOrder(){
        //1、查询下单时间为 15分钟以前 并且 此时状态依然为【待支付】的所有订单
        //select * from orders where order_time <= 【当前时间 - 15分钟】 and status = 1;
        LocalDateTime orderTime = LocalDateTime.now().minusMinutes(15);
        List<Orders> ordersList = orderMapper.queryByOrderTimeAndStatus(orderTime, Orders.PENDING_PAYMENT);

        //2、将这些订单的订单状态修改为：【已取消】，取消时间、取消原因
        if(ObjectUtil.isEmpty(ordersList)){
            return;
        }
        //update orders set status = 6,cacel_time = '',cacel_reason = '' where id = '';
        /*ordersList.forEach(o -> {
            o.setStatus(Orders.CANCELLED);
            o.setCancelTime(LocalDateTime.now());
            o.setCancelReason("订单超时自动取消");
            orderMapper.update(o);
        });*/

        //update orders set status = 6,cacel_time = '',cacel_reason = '' where id in ('','','');
        Orders setParams = Orders.builder().status(Orders.CANCELLED).cancelTime(LocalDateTime.now()).cancelReason("订单超时自动取消").build();
        Set<Long> ids = ordersList.stream().map(o -> o.getId()).collect(Collectors.toSet());
        orderMapper.batchUpdate(setParams,ids);
    }

    /**
     * 派送中未处理订单处理（周期：每天凌晨一点执行一次）
     */
//    @Scheduled(cron = "0 0 1 * * ?")
//    @Scheduled(cron = "0/5 * * * * ?")
    public void processUnCompletedOrder(){
        //1、查询下单时间为 60分钟以前 并且 此时状态依然为【派送中】的所有订单
        //select * from orders where order_time <= 【当前时间 - 60分钟】 and status = 4;
        LocalDateTime orderTime = LocalDateTime.now().minusMinutes(60);
        List<Orders> ordersList = orderMapper.queryByOrderTimeAndStatus(orderTime, Orders.DELIVERY_IN_PROGRESS);

        //2、将这些订单的订单状态修改为：【已完成】
        if(ObjectUtil.isEmpty(ordersList)){
            return;
        }

        //update orders set status = 5  where id in ('','','');
        Orders setParams = Orders.builder().status(Orders.COMPLETED).build();
        Set<Long> ids = ordersList.stream().map(o -> o.getId()).collect(Collectors.toSet());
        orderMapper.batchUpdate(setParams,ids);
    }

}
